package xiongguanweb

import grails.converters.JSON
import org.slf4j.Logger
import org.slf4j.LoggerFactory
import xiongguanweb.http.HttpClient
import xiongguanweb.http.OnResponseListener
import xiongguanweb.http.RequestParams

import javax.servlet.http.HttpSession

class LoginController {

    private static Logger logger = LoggerFactory.getLogger(LoginController.class)

    LoginService loginService

    //用户登录
    def authToken() {
        def username = "${params.username}"
        def pwd = "${params.password}"
        println username
        RequestParams params = new RequestParams()
        params.putBody("loginName", username)
        params.putBody("pwd", pwd)
        params.putHead("trcode", "1048")
        def resData = [:]
        HttpClient.me().post(session, params, new OnResponseListener() {
            @Override
            void onSuccess(int errorcode, String errormsg, String data) {
                session.setAttribute("username",username)
                resData.errorcode = errorcode
            }


            @Override
            void onFailure(int errorcode, String errormsg) {
                resData.errorcode = errorcode
                resData.errormsg = errormsg

            }

            @Override
            void onTokenExpired(int errorcode, HttpSession sion) {
                resData.errorcode = 401

            }
        })
        render resData as JSON
    }

    /**
     * 控件下载
     */
    def dowControl() {
//        def apkFilePath = request.getSession().getServletContext().getRealPath("apk/PowerEnterZBANK.exe")
        def apkFilePath = "c:\\workspace\\PowerEnterLZBANK.exe"
        def apkFile = new File("${apkFilePath}")
        logger.info("file==${apkFilePath}")
        if (apkFile.exists()) {
            BufferedOutputStream bos = null
            BufferedInputStream bis = null
            try {
                long apkFileSize = apkFile.size()
                response.setHeader("Content-disposition", "attachment; filename=PowerEnterZBANK.exe")
                response.contentType = "application/x-rarx-rar-compressed"
//                response.setHeader("Content-Length", "${apkFileSize}")
                bos = new BufferedOutputStream(response.outputStream)
                bis = new BufferedInputStream(new FileInputStream(apkFile))
                byte[] buffer = new byte[1024]
                int len = -1
                while ((len = bis.read(buffer)) != -1) {
                    bos.write(buffer, 0, len)
                    bos.flush()
                }
                bos.flush()
            } catch (Exception e) {
                logger.error(e.getLocalizedMessage())
            } finally {
                if (bis != null) {
                    bis.close()
                }
                if (bos != null) {
                    bos.close()
                }
            }
        } else {
            render "fail"
        }
    }

    /**退出登录
     *
     * @return
     */
    def loginout() {
        RequestParams params = new RequestParams()
        params.putHead("trcode", "1009")
        params.putHead("Jwt", session.getAttribute(AppConfig.TOKEN))
        def resData = [:]
        HttpClient.me().post(session, params, new OnResponseListener() {
            @Override
            void onSuccess(int errorcode, String errormsg, String data) {
                session.invalidate()
                redirect(uri: "/login")
            }

            @Override
            void onFailure(int errorcode, String errormsg) {
                session.invalidate()
                redirect(uri: "/login")

            }

            @Override
            void onTokenExpired(int errorcode, HttpSession sion) {
                resData.errorcode = 401
                session.invalidate()
                redirect(uri: "/login")

            }
        })
    }
}
